package L_5_8.demo02;

import java.util.Arrays;
import java.util.Comparator;

//自定义类型进行比较，要实现Comparable接口
class Student implements Comparable<Student> {
    public int age;
    public String name;

    public Student (int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString () {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public int compareTo (Student o) {
//        if (this.age > o.age) {
//            return 1;
//        } else if (this.age < o.age) {
//            return - 1;
//        } else return 0;
        return this.age - o.age;
    }
}

//对类的侵入性不强，可以和类里面的方法共存
class AgeComapare implements Comparator<Student> {

    @Override
    public int compare (Student o1, Student o2) {
        return o1.age - o2.age;
    }
}

class NameCompare implements Comparator<Student> {
    @Override
    public int compare (Student o1, Student o2) {
        return o1.name.compareTo (o2.name);
    }
}


public class test {
    //对自定义类型的冒泡排序

    //这里的Comparable接口如果加上<Student>，那么这里的compareTo方法就不能用于Sort里面的比较
    //这两个compareTo方法不同，一个是普通方法，一个是重写后用于自定义的数据类型的比较方法
    public static void Sort (Comparable[] comparable) {
        for (int i = 0; i < comparable.length - 1; i++) {
            for (int j = 0; j < comparable.length - 1 - i; j++) {
                if (comparable[j].compareTo (comparable[j + 1]) > 0) {
                    Comparable temp = comparable[j];
                    comparable[j] = comparable[j + 1];
                    comparable[j + 1] = temp;
                }
            }

        }
    }


    public static void main (String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student (10, "liu");
        students[1] = new Student (30, "luo");
        students[2] = new Student (20, "wang");

        //Arrays.sort (students);
        Sort (students);

        //System.out.println (Arrays.toString (students));

        //该比较方法如果要实现通过Student的名字进行排序，需要在类里面再加入一个新的比较方法
        //这种写法对类的侵入性比较强
        //有一种更好的方法是把比较方法写在类的外面

        AgeComapare c1 = new AgeComapare ();
        System.out.println (c1.compare (students[0], students[1]));

        NameCompare c2 = new NameCompare ();
        System.out.println (c2.compare (students[0], students[1]));
    }

    public static void main1 (String[] args) {
        Student s1 = new Student (10, "huang");
        Student s2 = new Student (20, "hong");

        //System.out.println (s1.compareTo (s2));
    }
}
